package com.htdz.filter;

import com.htdz.entity.Users;
import com.htdz.entity.UsersInfo;
import com.htdz.util.CommonRedisUtil;
import com.htdz.util.RedisUtil;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Aspect
@Component
public class LoginInterceptor implements HandlerInterceptor {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    public RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.info("---------------------开始进入请求地址拦截----------------------------");
        //单机，不采用redis保存session处理方式
        //String parentTId = httpServletRequest.getParameter("parentTId");
        HttpSession session = httpServletRequest.getSession();
        //session.setAttribute("parentTId",parentTId);
        UsersInfo userInfo = (UsersInfo)session.getAttribute("usersInfo");
        if(userInfo!=null){
            logger.info(".................true");
            return true;
        }
        else{
            //PrintWriter printWriter = httpServletResponse.getWriter();
            //printWriter.write("{code:0,message:\"会话已过期，请重新登录!\"}");
            logger.info(".................false");
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/");//重新指向登录地址
            return false;
        }

/*        //默认所有链接增加userId参数，用于判断redis用户是否已登录
        String[] userIds = httpServletRequest.getParameterValues("usersId");
        if(userIds == null){
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/");//重新指向登录地址
            return false;
        }
        String key = "sessionUser_"+userIds[0];

        if(redisUtil.hasExistKey(key)){//redis中是否已存在此userInfo
            return true;
        }else {
            httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/");//重新指向登录地址
            return false;
        }*/
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info("---------------------请求地址拦截结束----------------------------");
    }
}
